package cn.janescott.inner.space.data.system.service;

import cn.janescott.inner.space.data.system.dao.UserRepository;
import cn.janescott.inner.space.data.system.dto.AccountStatusDTO;
import cn.janescott.inner.space.data.system.dto.UserDTO;
import cn.janescott.inner.space.data.system.dto.UserSummaryDTO;
import cn.janescott.inner.space.data.system.entity.User;
import cn.janescott.inner.space.lib.support.service.ServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author scott
 * @date 2018/7/25
 */
@Service
public class UserServiceImpl extends ServiceSupport implements UserService {

    private UserRepository repository;

    @Autowired(required = false)
    public void setRepository(UserRepository repository) {
        this.repository = repository;
    }

    @Override
    public UserDTO findByUsername(String username) {
        User user = repository.findOneByUsername(username);
        if (null == user) {
            return null;
        }
        return convert(new UserDTO(), user);
    }

    @Override
    public AccountStatusDTO findAccountStatusByUserId(Long userId) {
        if (null == userId) {
            throw new IllegalArgumentException("user id cannot be null!");
        }
        User user = repository.findOneByUserId(userId);
        if (null == user) {
            return null;
        }
        return convert(new AccountStatusDTO(), user.getAccountStatus());
    }

    @Override
    public UserSummaryDTO findSummaryByUsername(String username) {
        User user = repository.findOneByUsername(username);
        if (null == user) {
            return null;
        }

        UserSummaryDTO userSummaryDTO = UserSummaryDTO.newInstance();
        convert(userSummaryDTO.getUser(), user);
        if (null != user.getAccountStatus()) {
            convert(userSummaryDTO.getAccount(), user.getAccountStatus());
        }
        return userSummaryDTO;
    }
}
